/**
 * @file 主app
 * @author [fanxingguang]
 */
'use strict';
var express = require('express');
var path = require('path');
var ueditor = require('ueditor');
// var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var adminRoutes = require('./routes/admin');
var apiRoutes = require('./routes/api');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
// app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
    secret: 'mywifeiswangyan', // 建议使用 128 个字符的随机字符串
    cookie: {maxAge: 60 * 1000}
}));

// app.use(function (req, res, next) {
//     next();
// });
app.use('/', routes);
app.use('/', apiRoutes);
app.use('/api', apiRoutes);
app.use('/admin', adminRoutes);
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'admin/dist')));
app.use(express.static(path.join(__dirname, 'www/dist')));
app.use('/ue', ueditor(path.join(__dirname, 'public'), function (req, res, next) {
    // ueditor 客户发起上传图片请求
    if (req.query.action === 'uploadimage') {
        var imgUrl = '/images/ueditor/';
        // 你只要输入要保存的地址 。保存操作交给ueditor来做
        res.ue_up(imgUrl);
    }
    // 客户端发起图片列表请求
    else if (req.query.action === 'listimage') {
        var dirUrl = '/images/ueditor/';
        res.ue_list(dirUrl); // 客户端会列出 dirUrl 目录下的所有图片
    }
    // 客户端发起其它请求
    else {
        res.setHeader('Content-Type', 'application/json');
        // 这里的路径要加载对否则就不能上传图片。如果你下载的是JSP那就对应jsp目录
        res.redirect('/asset/ueditor/php/config.json');
    }
}));
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function (err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});


module.exports = app;
